<template>
  <div ref="containerRef" style="height: 100%"></div>
</template>

<script setup>
import { nextTick, onMounted, onBeforeUnmount, ref } from 'vue'
import * as echarts from 'echarts'

const props = defineProps({
  /**
   * 图表点击事件
   */
  chartClick: {
    type: Function,
    required: false,
  },
})
const $emits = defineEmits({
  /**
   * echarts挂载完毕，且执行了setOption之后，会触发该事件(仅触发一次)
   * @param {*} echartInstance echart实例
   */
  mountedToDom: echartInstance => true,
})

const containerRef = ref()

let myChart = null
let option = null
let isMounted = false

const observer = new ResizeObserver(() => {
  chartContainerResize()
})

function getEchartInstance(){
  return myChart
}

onMounted(() => {
  const containerDom = containerRef.value
  if (!containerDom) return

  myChart = echarts.init(containerDom)
  if (option) {
    setOption(option)
    emitMountedToDomEvt()
  }
  if (props.chartClick) {
    myChart.on('click', function (params) {
      props.chartClick(params)
    })
  }
  observer.observe(containerDom)
})

onBeforeUnmount(() => {
  const containerDom = containerRef.value
  if (!containerDom) return

  if (props.chartClick) {
    myChart.off('click')
  }
  myChart.dispose()
  myChart = null
  observer.unobserve(containerDom)
  observer.disconnect()
})

function chartContainerResize() {
  if (myChart) {
    myChart.resize()
  }
}
/**
 * 初始化/更新 配置
 * @param {ECOption} option
 */
function setOption(option) {
  if (myChart) {
    myChart.setOption(option)
    emitMountedToDomEvt()
  }
}
function hideLoading() {
  if (!myChart) return
  myChart.hideLoading()
}
function showLoading({ text, color, textColor } = { text: '加载中...', color: '#0183FF', textColor: '#000' }) {
  if (!myChart) return
  myChart.showLoading({
    text,
    color,
    textColor,
    //遮罩颜色
    maskColor: 'rgba(247, 248, 250, 0.8)',
    zlevel: 0,
    // 字体大小。从 `v4.8.0` 开始支持。
    fontSize: 14,
    // 是否显示旋转动画（spinner）
    showSpinner: true,
    // 旋转动画（spinner）的半径
    spinnerRadius: 10,
    // 旋转动画（spinner）的线宽
    lineWidth: 5,
  })
}
function emitMountedToDomEvt() {
  if (!isMounted) {
    isMounted = true
    nextTick(() => {
      window.requestAnimationFrame(() => {
        $emits('mountedToDom', myChart)
      })
    })
  }
}
defineExpose({ setOption, showLoading, hideLoading,getEchartInstance })
</script>
